<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>IMDb on The Russian Lullaby</title><link>https://www.therussianlullaby.dev/tags/imdb/</link><description>Recent content in IMDb on The Russian Lullaby</description><generator>Hugo -- gohugo.io</generator><language>en-US</language><lastBuildDate>Mon, 30 Nov 2026 00:00:00 +0100</lastBuildDate><atom:link href="https://www.therussianlullaby.dev/tags/imdb/index.xml" rel="self" type="application/rss+xml"/><item><title>Implementing a secondary Drupal migration to enrich existing data</title><link>https://www.therussianlullaby.dev/blog/drupal-migrations-seven-secondary-migrations-more-cowbell/</link><pubDate>Mon, 30 Nov 2026 00:00:00 +0100</pubDate><guid>https://www.therussianlullaby.dev/blog/drupal-migrations-seven-secondary-migrations-more-cowbell/</guid><enclosure url="https://www.therussianlullaby.dev/images/post/davidjguru_drupal_migrations_secondary_data_enrichment_main.jpg" length="102935" type="image/jpeg"/><media:content url="https://www.therussianlullaby.dev/images/post/davidjguru_drupal_migrations_secondary_data_enrichment_main.jpg" medium="image" type="image/jpeg"/><media:thumbnail url="https://www.therussianlullaby.dev/images/post/davidjguru_drupal_migrations_secondary_data_enrichment_main.jpg"/><description>How to implement a secondary Drupal migration that adds content and enriches existing entities with Migrate API and external sources.</description><content:encoded><![CDATA[<p>In <a href="/blog/drupal-migrations-six-rick-and-migraty-experience-merging-data-from-different-sources/">the previous article in this series</a>, we implemented an end-to-end migration project: the <a href="https://gitlab.com/davidjguru/rick-and-migraty"><strong>Rick and Migraty</strong> experience</a>. It populates a Drupal installation from several data sources. The <a href="https://rickandmortyapi.com/">Rick and Morty API</a> supplies the primary catalogue, <a href="https://www.tvmaze.com/">TVmaze</a> contributes episode data, and the <a href="https://www.fandom.com/">Fandom</a> content hub adds editorial context. <strong>The result is a small content domain made up of characters, locations, episodes, and the relationships among them—a map of several facets of the animated series&rsquo; universe.</strong></p>
<p>After completing that first migration, I considered a new feature: <strong>plotting the rating of every episode</strong> so that visitors could follow the evolution of the series, compare seasons, and spot the highest- and lowest-rated episodes at a glance. <strong>What initially looked like a visualisation task exposed two limitations in the migrated dataset:</strong> <strong>a)</strong> we retained only one rating source, and <strong>b)</strong> the Rick and Morty universe did not end with the regular series; it also included <a href="https://rickandmorty.fandom.com/wiki/Rick_and_Morty:_The_Anime"><em>Rick and Morty: The Anime</em></a> and <a href="https://rickandmorty.fandom.com/wiki/The_Non-Canonical_Adventures"><em>The Non-Canonical Adventures</em></a>.</p>
<p>The chart therefore changed the technical question. It was no longer just a matter of drawing existing data, but of <strong>extending and enriching a completed migration without restarting it, duplicating entities, or turning optional sources into dependencies of the primary catalogue</strong>. This seventh article explains the solution implemented in <a href="https://gitlab.com/davidjguru/rick-and-migraty">Rick and Migraty</a>: a secondary migration that adds complementary works and episodes, locates episodes already stored in Drupal, and attaches new rating observations with their provenance. <strong>Once those data are in place, we can build the ratings-tracking chart.</strong></p>
<p><strong>Note:</strong> As of 30 November 2026, this article contains approximately 7,900 words and 65,000 characters, with an estimated reading time of 40–48 minutes.</p>
<p><strong>Table of contents</strong></p>
<span class="post-toc" aria-hidden="true"></span>

<!-- raw HTML omitted -->
<ul>
<li><a href="#0-tldr">0. TL;DR</a></li>
<li><a href="#1-the-starting-point-rick-and-migraty">1. The starting point: Rick and Migraty</a></li>
<li><a href="#2-when-a-chart-reveals-a-data-problem">2. When a chart reveals a data problem</a>
<ul>
<li><a href="#21-first-issue-more-works-than-the-regular-series">2.1. First issue: more works than the regular series</a></li>
<li><a href="#22-second-issue-one-observation-is-not-enough-for-comparison">2.2. Second issue: one observation is not enough for comparison</a></li>
</ul>
</li>
<li><a href="#3-what-to-require-from-the-new-sources">3. What to require from the new sources</a></li>
<li><a href="#4-the-selected-sources-and-their-responsibilities">4. The selected sources and their responsibilities</a></li>
<li><a href="#5-designing-a-secondary-migration">5. Designing a secondary migration</a>
<ul>
<li><a href="#51-the-primary-migration-is-a-verifiable-precondition">5.1. The primary migration is a verifiable precondition</a></li>
<li><a href="#52-the-boundary-is-additive-extend-do-not-rebuild">5.2. The boundary is additive: extend, do not rebuild</a></li>
<li><a href="#53-idempotency-starts-with-identity">5.3. Idempotency starts with identity</a></li>
<li><a href="#54-isolating-providers-means-isolating-steps-and-failures">5.4. Isolating providers means isolating steps and failures</a></li>
<li><a href="#55-resuming-requires-persisted-progress-and-verified-effects">5.5. Resuming requires persisted progress and verified effects</a></li>
</ul>
</li>
<li><a href="#6-creating-the-complementary-works-and-episodes">6. Creating the complementary works and episodes</a>
<ul>
<li><a href="#61-which-plugins-do-we-need">6.1. Which plugins do we need?</a></li>
</ul>
</li>
<li><a href="#7-locating-existing-entities-to-enrich-them">7. Locating existing entities to enrich them</a>
<ul>
<li><a href="#a-lookup-is-not-a-title-search">A lookup is not a title search</a></li>
<li><a href="#three-kinds-of-lookup-in-a-drupal-migration">Three kinds of lookup in a Drupal migration</a></li>
<li><a href="#the-source-prepares-the-external-half-of-the-identity">The source prepares the external half of the identity</a></li>
<li><a href="#resolving-the-receiving-entity-in-the-process-pipeline">Resolving the receiving entity in the process pipeline</a></li>
<li><a href="#enrichment-does-not-mean-modifying-the-episode-directly">Enrichment does not mean modifying the episode directly</a></li>
<li><a href="#adopting-data-that-predates-the-migration-map">Adopting data that predates the migration map</a></li>
<li><a href="#the-complete-journey-of-an-imdb-row">The complete journey of an IMDb row</a></li>
<li><a href="#myshows-applies-the-same-principle-with-a-different-identity">MyShows applies the same principle with a different identity</a></li>
</ul>
</li>
<li><a href="#8-orchestrating-a-resumable-run">8. Orchestrating a resumable run</a></li>
<li><a href="#9-testing-the-integration-and-building-the-ratings-area">9. Testing the integration and building the ratings area</a></li>
<li><a href="#10-patterns-worth-keeping">10. Patterns worth keeping</a></li>
<li><a href="#11-running-the-secondary-migration-from-the-terminal">11. Running the secondary migration from the terminal</a>
<ul>
<li><a href="#111-preparing-the-primary-migration">11.1. Preparing the primary migration</a></li>
<li><a href="#112-running-the-secondary-steps-with-drush">11.2. Running the secondary steps with Drush</a></li>
<li><a href="#113-verifying-the-result-and-resuming-after-a-failure">11.3. Verifying the result and resuming after a failure</a></li>
</ul>
</li>
<li><a href="#12-wq">12. :wq!</a></li>
</ul>
<!-- raw HTML omitted -->
<hr>
<h2 id="0-tldr">0. TL;DR</h2>
<p><strong>The first Rick and Migraty migration had already created a stable catalogue for the main series.</strong> The requirement to compare episode ratings exposed two gaps: complementary franchise content was missing, and a single rating provider was not enough for meaningful comparison.</p>
<p>The solution was not to rerun the whole process or keep expanding the primary migration indefinitely. Instead, we implemented a <strong>secondary migration</strong> with two responsibilities:</p>
<ol>
<li>Create works and episodes that do not yet exist in Drupal.</li>
<li>Locate previously migrated episodes and attach rating observations from additional providers.</li>
</ol>
<p>We use <code>migration_lookup</code> to associate newly created episodes with work entities produced by an earlier migration. IMDb enrichment requires a dedicated migration: a source plugin prepares rating rows, while two process plugins resolve both the receiving episode and any observation imported before the new migration map existed. The work is divided into resumable steps and ultimately feeds a new ratings and charting area.</p>
<blockquote>
<p>A secondary migration does not necessarily repeat the initial migration. It can depend on that migration&rsquo;s result, create only what is missing, and enrich entities that already exist.</p>
</blockquote>
<p>
<span class="post-figure">
  <img src="/images/post/davidjguru_drupal_migrations_secondary_data_enrichment_two.webp" alt="Updated menu with the new secondary-migration action." loading="lazy" decoding="async">
  <span class="post-figure__caption">New primary-menu actions: secondary migration and ratings area.</span>
</span>

</p>
<p>Welcome, then, to the complementary process: <strong>The More Cowbell Migration!</strong> The new features are available on the <a href="https://gitlab.com/davidjguru/rick-and-migraty">project&rsquo;s main branch</a> and included in <a href="https://gitlab.com/davidjguru/rick-and-migraty/-/tags/2.0.0">tag 2.0.0</a>. Installation and build instructions are available in the <a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/README.md">project README</a> and in the <a href="/blog/drupal-migrations-six-rick-and-migraty-experience-merging-data-from-different-sources/">previous article</a>.</p>
<p>After running both the primary and secondary processes, the ratings area contains the full set of data and comparisons:</p>
<p>
<span class="post-figure">
  <img src="/images/post/davidjguru_drupal_migrations_secondary_data_enrichment_three.webp" alt="The new episode-ratings area." loading="lazy" decoding="async">
  <span class="post-figure__caption">Episode ratings generated from the integrated data.</span>
</span>

</p>
<p>The ratings area is available even before the secondary migration runs, but it will then show only the regular series and will not expose combined values from the additional sources: arithmetic mean, median, and vote-weighted mean.</p>
<p>
<span class="post-figure">
  <img src="/images/post/davidjguru_migrations_secondary_data_enrichment_four-1200x800.jpg" alt="Poster announcing the new migration in a deliberately dissonant way." loading="lazy" decoding="async">
  <span class="post-figure__caption">More episodes, more data, more ratings&hellip; MORE COWBELL.</span>
</span>

</p>
<blockquote>
<p>&ldquo;I got a fever, and the only prescription is more cowbell!&rdquo;</p>
<p>— <strong>Christopher Walken as Bruce Dickinson</strong></p>
</blockquote>
<p>And now, as in a Guy Ritchie film, let us freeze the frame, rewind, and say: <em><strong>You are probably wondering how I got here&hellip;</strong></em></p>
<h2 id="1-the-starting-point-rick-and-migraty">1. The starting point: Rick and Migraty</h2>
<p><strong>The first version of the project had a deliberately clear boundary: the Rick and Morty API defined the identity of the main series&rsquo; characters, locations, and episodes.</strong> TVmaze and Fandom could enrich selected fields, but they could not silently decide which entities belonged to the catalogue or replace their identity.</p>
<p>That division of responsibilities made the process predictable:</p>
<ol>
<li>Import the main work.</li>
<li>Import characters, locations, and episodes.</li>
<li>Build their relationships.</li>
<li>Complete descriptions and provenance from secondary sources.</li>
<li>Verify the result before considering the migration complete.</li>
</ol>
<p>The previous article, <a href="/blog/drupal-migrations-six-rick-and-migraty-experience-merging-data-from-different-sources/">Drupal Migrations (VI): Rick and Migraty, combining data from several sources</a>, describes that design in detail. What matters here is that <strong>we already had persisted data and a stable identity for every entity</strong>. The secondary migration had to respect that state.</p>
<p>Changing the first pipeline to absorb every later requirement would mix two different moments: <strong>a)</strong> building the minimum catalogue that makes the site useful and <strong>b)</strong> extending it when new use cases appear. It would also turn optional or less reliable providers into requirements for a usable result. <strong>I chose a different direction.</strong></p>
<h2 id="2-when-a-chart-reveals-a-data-problem">2. When a chart reveals a data problem</h2>
<p>The original idea was simple: create <strong>an episode-ratings chart</strong>. I wanted to represent the series as a trajectory, filter it by season or score, and open an episode profile from each point.</p>
<p>Before building the interface, I reviewed the data that could feed the chart. Two problems appeared.</p>
<h3 id="21-first-issue-more-works-than-the-regular-series">2.1. First issue: more works than the regular series</h3>
<p>The migrated catalogue described the main series but left out two related collections:</p>
<ul>
<li><em><strong>Rick and Morty: The Anime</strong></em>, with its own continuity and episode catalogue;</li>
<li><em><strong>The Non-Canonical Adventures</strong></em>, a collection of shorts that should not be mixed with regular seasons.</li>
</ul>
<p>These were not extra seasons of the same work. <strong>We needed to add them as independent works, retain their context, and connect every episode to the correct work.</strong></p>
<h3 id="22-second-issue-one-observation-is-not-enough-for-comparison">2.2. Second issue: one observation is not enough for comparison</h3>
<p>Episodes already had a TVmaze rating. That value was useful for display, but it could not support provider comparison or explain why sources might disagree. <strong>Overwriting it with another score would not solve the problem:</strong> we would lose provenance and turn the most recent import into an accidental truth.</p>
<p>The chart needed a richer model: several observations per episode, each with a provider, scale, vote count, external identifier, source URL, and retrieval date. The interface would come later; first we had to complete the domain model and the ETL process that supplied it.</p>
<h2 id="3-what-to-require-from-the-new-sources">3. What to require from the new sources</h2>
<p>The search could not stop at finding a page that displayed the right value. <strong>The sources had to fit an open, reproducible project.</strong> I used criteria similar to those applied to the primary migration:</p>
<ul>
<li><strong>Open or free access</strong>, without requiring a closed commercial service to run the example.</li>
<li><strong>Current data</strong>, obtained from a maintained API or dataset rather than copied manually into the repository.</li>
<li><strong>Stable identifiers</strong>, so records can be joined without translated titles or ambiguous searches.</li>
<li><strong>Verifiable provenance</strong>, including provider, URL, and usage conditions that can be stored with the value.</li>
<li><strong>A processable format</strong>, whether remote JSON, downloadable files, or responses a source plugin can normalise.</li>
<li><strong>Isolatable failures</strong>, because an unavailable secondary source must not make the primary catalogue unusable.</li>
</ul>
<p>That last requirement proved decisive. <strong>A deprecated API or a large dataset can remain useful when its absence does not break the base process</strong> and the affected step can be retried independently.</p>
<h2 id="4-the-selected-sources-and-their-responsibilities">4. The selected sources and their responsibilities</h2>
<p>The research produced a small set of sources, each with a specific responsibility. Some were already present in the primary migration, but not all create entities or act on the same content.</p>
<table>
<thead>
<tr>
<th><strong>Source</strong></th>
<th><strong>Access method</strong></th>
<th><strong>Responsibility in the secondary migration</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>Wikidata</td>
<td>Records identified by QID</td>
<td>Identify and describe the two complementary works.</td>
</tr>
<tr>
<td>TVmaze</td>
<td>Public episode API</td>
<td>Create the <em>Anime</em> and <em>Non-Canonical Adventures</em> catalogues with stable episode IDs.</td>
</tr>
<tr>
<td>Fandom</td>
<td>Editorial franchise catalogue</td>
<td>Independently verify the expected set of 36 non-canonical shorts.</td>
</tr>
<tr>
<td>MyShows</td>
<td>Public read-only API</td>
<td>Add rating observations to the non-canonical shorts.</td>
</tr>
<tr>
<td>IMDb</td>
<td>Downloadable non-commercial datasets</td>
<td>Add scores and vote counts to existing main-series episodes.</td>
</tr>
</tbody>
</table>
<p><strong>This split prevents any source from receiving more authority than it should have.</strong> Wikidata identifies works, TVmaze supplies episode catalogues, Fandom helps verify coverage, and rating providers contribute observations. The <a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/docs/docs/migrations/optional-franchise-enrichment.md">optional-enrichment documentation</a> records the full contract and approved identifiers.</p>
<p>Operationally, the providers also differ. IMDb publishes compressed files that we download and stream. MyShows exposes a deprecated but still useful API, kept optional and isolated. TVmaze is queried through fixed IDs rather than title search. If a catalogue changes unexpectedly, the process fails for review instead of silently accepting different content.</p>
<h2 id="5-designing-a-secondary-migration">5. Designing a secondary migration</h2>
<p><em><strong>Secondary migration</strong></em> is not an official Drupal plugin type or Migrate API category. In this project, it is the name of an optional operational contract that runs <strong>after</strong> the primary migration.</p>
<p>The contract has five properties. They are not five consecutive steps and do not all belong to one class; they are invariants distributed across input validation, YAML definitions, lookup plugins, and orchestration.</p>
<table>
<thead>
<tr>
<th><strong>Contract property</strong></th>
<th><strong>Implementation decision</strong></th>
<th><strong>Primary mechanism</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="#51-the-primary-migration-is-a-verifiable-precondition">5.1</a> <strong>Startup:</strong> the primary migration must be complete.</td>
<td>Treat persisted output as a precondition rather than an assumption.</td>
<td><code>PrimaryMigrationReadiness</code> and repeated endpoint validation.</td>
</tr>
<tr>
<td><a href="#52-the-boundary-is-additive-extend-do-not-rebuild">5.2</a> <strong>Operation:</strong> the primary catalogue must not be destructively changed.</td>
<td>Add separate works, episodes, and observations without reverting the first migration.</td>
<td><code>OptionalEnrichmentOrchestrator</code> and independent optional migrations.</td>
</tr>
<tr>
<td><a href="#53-idempotency-starts-with-identity">5.3</a> <strong>Idempotency:</strong> retries must not duplicate content.</td>
<td>Assign stable identities and retain source-to-destination mappings.</td>
<td>Source keys, Migrate maps, <code>--update</code>, and deterministic lookups.</td>
</tr>
<tr>
<td><a href="#54-isolating-providers-means-isolating-steps-and-failures">5.4</a> <strong>Isolation:</strong> one optional provider must not block the others.</td>
<td>Make every external integration independently executable and configurable.</td>
<td>Provider-specific steps and <code>RICK_AND_MIGRATY_OPTIONAL_*</code> variables.</td>
</tr>
<tr>
<td><a href="#55-resuming-requires-persisted-progress-and-verified-effects">5.5</a> <strong>Persistence:</strong> interruption must not require a full restart.</td>
<td>Store step outcomes and retry only incomplete work.</td>
<td>Drupal State, typed outcomes, and effect verification.</td>
</tr>
</tbody>
</table>
<p>This table serves as both a compact requirements catalogue and a high-level design map. The components described below each implement a specific part of that contract.</p>
<h3 id="51-the-primary-migration-is-a-verifiable-precondition">5.1. The primary migration is a verifiable precondition</h3>
<p><strong>The first property establishes how we certify that the primary migration has actually run and finished.</strong> This is why the contract calls for a PHP class devoted to checking that precondition.</p>
<p>I therefore implemented <a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_migrate/src/PrimaryMigrationReadiness.php"><code>PrimaryMigrationReadiness</code></a>. Its responsibility is neither to execute the primary migration nor to order a YAML definition. It answers a domain question: <strong>does Drupal contain a sufficiently complete primary catalogue to accept extensions?</strong></p>
<p>Knowing that a command completed at some point is not enough. <strong>The class checks the main entities,</strong> the relationships between episodes and characters, the relationships between locations and residents, and the completion of the Fandom enrichment batches. The secondary migration depends on the <strong>persisted result</strong> of the first migration, not merely its execution history.</p>
<p><strong>The first check queries the entity storages directly.</strong> <code>count()</code> does not read a previous run status; it asks Drupal how many entities really exist at that moment:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-php" data-lang="php">private function count(string $entityTypeId): int {
  return (int) $this-&gt;entityTypeManager-&gt;getStorage($entityTypeId)
    -&gt;getQuery()
    -&gt;accessCheck(FALSE)
    -&gt;count()
    -&gt;execute();
}
</code></pre></div><p><code>isComplete()</code> uses that method to count characters, locations, episodes, and works. <strong>It then compares the result with the minimum catalogue that the primary migration must have produced:</strong></p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-php" data-lang="php">$counts = [
  &#39;characters&#39; =&gt; $this-&gt;count(&#39;rick_and_migraty_character&#39;),
  &#39;locations&#39; =&gt; $this-&gt;count(&#39;rick_and_migraty_location&#39;),
  &#39;episodes&#39; =&gt; $this-&gt;count(&#39;rick_and_migraty_episode&#39;),
  &#39;works&#39; =&gt; $this-&gt;count(&#39;rick_and_migraty_work&#39;),
];
$coreReady = $counts[&#39;characters&#39;] &gt;= 826
  <span style="color:#a61717;background-color:#e3d2d2">&amp;&amp;</span> $counts[&#39;locations&#39;] &gt;= 126
  <span style="color:#a61717;background-color:#e3d2d2">&amp;&amp;</span> $counts[&#39;episodes&#39;] &gt;= 51
  <span style="color:#a61717;background-color:#e3d2d2">&amp;&amp;</span> $counts[&#39;works&#39;] &gt;= 1
  <span style="color:#a61717;background-color:#e3d2d2">&amp;&amp;</span> $this-&gt;hasRelationship(&#39;rick_and_migraty_episode&#39;, &#39;characters&#39;)
  <span style="color:#a61717;background-color:#e3d2d2">&amp;&amp;</span> $this-&gt;hasRelationship(&#39;rick_and_migraty_location&#39;, &#39;residents&#39;);

if (!$coreReady) {
  return FALSE;
}
</code></pre></div><p><strong>Counts prove that entities exist, but not that the main relationships were populated.</strong> That is why the same block calls <code>hasRelationship()</code> twice. The method looks for at least one entity whose reference field contains data:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-php" data-lang="php">private function hasRelationship(string $entityTypeId, string $fieldName): bool {
  return $this-&gt;entityTypeManager-&gt;getStorage($entityTypeId)
    -&gt;getQuery()
    -&gt;accessCheck(FALSE)
    -&gt;exists($fieldName)
    -&gt;range(0, 1)
    -&gt;execute() !== [];
}
</code></pre></div><p>More precisely, <code>isComplete()</code> requires at least one episode with associated characters and one location with residents. <strong>This is not an exhaustive validation of every relationship,</strong> but it prevents a catalogue containing only disconnected entities from being considered ready.</p>
<p>Finally, <strong>the class performs a different check for the Fandom enrichment.</strong> Those batches do leave an explicit list of completed steps in Drupal State. The class retrieves that value, rejects anything that is not a step identifier, and makes sure none of the steps returned by <code>fandomStepIds()</code> is missing:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-php" data-lang="php">$completed = $this-&gt;state-&gt;get(self::COMPLETED_STEPS_STATE_KEY, []);
$completed = is_array($completed)
  ? array_values(array_filter($completed, &#39;is_string&#39;))
  : [];

return array_diff($this-&gt;fandomStepIds(), $completed) === [];
</code></pre></div><p>Here we do consult persisted execution history, but never in isolation. The class reaches this comparison only after verifying that the main entities and relationships still exist. <strong>The precondition therefore combines evidence from the current domain state with the record of the batches that completed the enrichment.</strong></p>
<p>This validation runs when the flow is opened, when it starts, and before protected operations execute. Consequently, <strong>a direct request to an endpoint cannot bypass the precondition already displayed by the interface.</strong></p>
<p>The dependency declared in Migrate YAML remains useful for ordering specific migrations, but it cannot express this complete functional state on its own. The two layers complement each other:</p>
<ul>
<li><code>migration_dependencies</code> orders related migrations inside Migrate API;</li>
<li><code>PrimaryMigrationReadiness</code> verifies that the application as a whole is ready for optional enrichment.</li>
</ul>
<h3 id="52-the-boundary-is-additive-extend-do-not-rebuild">5.2. The boundary is additive: extend, do not rebuild</h3>
<p>The second property is enforced by restricting what the secondary plan may do. It never calls <code>rollback</code>, <code>reset</code>, or deletion commands. It imports optional works, complementary episodes, and rating observations without rebuilding the characters, locations, episodes, and relationships produced by the primary migration.</p>
<p>The data model expresses the same boundary. IMDb and MyShows scores become related observation entities; they do not overwrite TVmaze&rsquo;s value. <em>The Anime</em> and <em>The Non-Canonical Adventures</em> have their own migrations rather than becoming extra source rows in the main-work definition.</p>
<p><strong>Secondary describes both a temporal dependency and an ownership restriction:</strong> the process may read and relate to the base catalogue, but it does not own its lifecycle. A provider failure therefore leaves a usable primary site behind.</p>
<h3 id="53-idempotency-starts-with-identity">5.3. Idempotency starts with identity</h3>
<p>The third property connects the contract with the implementation decisions developed in the next two sections. Flags and execution options such as <code>--update</code> cannot prevent duplicates on their own. First, <strong>every source row must present the same identity each time the migration runs:</strong></p>
<p><strong>Several kinds of identity appear in this workflow</strong> because not every operation creates the same kind of content:</p>
<ul>
<li>optional works use a stable <code>machine_id</code>;</li>
<li>complementary episodes retain the TVmaze episode ID;</li>
<li>IMDb observations use <code>tconst</code> as their source ID and store the destination observation in a Migrate map;</li>
<li>observations created before that map can be adopted through episode + provider + external ID.</li>
</ul>
<p>A visible title never becomes an accidental identity. Source keys allow Migrate to find previous destinations, while process plugins resolve existing entities when two systems do not share identifiers. <strong>Section 6 illustrates the first case by creating new works and episodes; Section 7 develops the second by enriching episodes that already exist in Drupal.</strong></p>
<h3 id="54-isolating-providers-means-isolating-steps-and-failures">5.4. Isolating providers means isolating steps and failures</h3>
<p>The fourth property takes shape in the plan defined by <a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_migrate/src/Optional/OptionalEnrichmentOrchestrator.php"><code>OptionalEnrichmentOrchestrator</code></a>. Although the browser presents a single action, <strong>the orchestrator keeps separate steps for optional works, each episode catalogue, MyShows ratings, and IMDb ratings.</strong></p>
<p>This separation has two consequences. First, each integration can be disabled through its own <code>RICK_AND_MIGRATY_OPTIONAL_*</code> variable without changing the meaning or usefulness of the primary catalogue. Second, a network failure, unexpected episode count, or unavailable provider remains attached to its own step; it does not require reverting completed steps or invalidate the base data.</p>
<p>This is not merely a matter of decomposing a large method into smaller functions. <strong>The isolation boundary matches the external risk boundary:</strong> every provider has its own availability, licence, format, and identity model. Each one therefore deserves a separate operational outcome that can be inspected and retried independently.</p>
<h3 id="55-resuming-requires-persisted-progress-and-verified-effects">5.5. Resuming requires persisted progress and verified effects</h3>
<p>After every step, the orchestrator stores an <code>imported</code>, <code>updated</code>, <code>skipped</code>, or <code>failed</code> outcome in Drupal State. A later run retains successful steps and retries failed ones, so reloading the browser does not force the whole process to start again.</p>
<p>Historical state, however, does not prove that data still exist. Before retaining a previous IMDb success, the orchestrator verifies that IMDb observations remain persisted. This distinction gives us two kinds of truth:</p>
<ol>
<li><strong>Orchestration truth:</strong> which step ran and what outcome it reported.</li>
<li><strong>Domain truth:</strong> which works, episodes, and ratings currently exist in Drupal.</li>
</ol>
<p>Drupal State retains the first; entities, source keys, and migration maps retain the second. Reliable resumption checks both wherever the risk requires it.</p>
<p>With this map in place, we can discuss the implementation without presenting one PHP class as though it were the entire secondary migration. <strong>The contract is fulfilled through composition:</strong> readiness verifies the precondition; separate migrations and observations protect the base catalogue; identities and lookups make repetition safe; provider-specific steps isolate failures; and persisted state makes the workflow resumable.</p>
<p>These properties are not five consecutive steps. <strong>The following sections deliberately change perspective and follow the data flow instead:</strong> first we create complementary content, then enrich existing entities, orchestrate a resumable run, and finally verify the result.</p>
<h2 id="6-creating-the-complementary-works-and-episodes">6. Creating the complementary works and episodes</h2>
<p>Once the <a href="#51-the-primary-migration-is-a-verifiable-precondition">primary precondition</a> is satisfied, the first ETL operation creates the two missing works. This small migration uses Drupal Core&rsquo;s <code>embedded_data</code> source plugin because its approved identity records belong directly in the YAML definition.</p>
<p>This is the simplest useful Migrate API case: the source rows live directly inside the migration definition. If you need the background, <a href="/blog/drupal-migrations-two-examples/">the second article in this series develops a similar embedded-data example</a> before moving on to CSV.</p>
<p><a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_migrate/migrations/rick_and_migraty_work_optional.yml"><code>rick_and_migraty_work_optional</code></a> contains the records:</p>







<div class="code-snippet">
  <div class="highlight"><div style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4">
<table style="border-spacing:0;padding:0;margin:0;border:0;width:auto;overflow:auto;display:block;"><tr><td style="vertical-align:top;padding:0;margin:0;border:0;">
<pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 1
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 2
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 3
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 4
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 5
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 6
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 7
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 8
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 9
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">10
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">11
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">12
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">13
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">14
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">15
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">16
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">17
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">18
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">19
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">20
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">21
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">22
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">23
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">24
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">25
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">26
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">27
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">28
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">29
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">30
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">31
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">32
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">33
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">34
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">35
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">36
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">37
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">38
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">39
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">40
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">41
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">42
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">43
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">44
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">45
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">46
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">47
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">48
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">49
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">50
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">51
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">52
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">53
</span></code></pre></td>
<td style="vertical-align:top;padding:0;margin:0;border:0;;width:100%">
<pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-yaml" data-lang="yaml"><span style="color:#000;font-weight:bold">id</span>:<span style="color:#bbb"> </span>rick_and_migraty_work_optional<span style="color:#bbb">
</span><span style="color:#bbb"></span><span style="color:#000;font-weight:bold">label</span>:<span style="color:#bbb"> </span><span style="color:#d14">&#39;Optional Rick and Migraty franchise works&#39;</span><span style="color:#bbb">
</span><span style="color:#bbb"></span><span style="color:#000;font-weight:bold">migration_group</span>:<span style="color:#bbb"> </span>rick_and_migraty<span style="color:#bbb">
</span><span style="color:#bbb">
</span><span style="color:#bbb"></span><span style="color:#000;font-weight:bold">source</span>:<span style="color:#bbb">
</span><span style="color:#bbb">  </span><span style="color:#000;font-weight:bold">plugin</span>:<span style="color:#bbb"> </span>embedded_data<span style="color:#bbb">
</span><span style="color:#bbb">  </span><span style="color:#000;font-weight:bold">data_rows</span>:<span style="color:#bbb">
</span><span style="color:#bbb">    </span><span style="color:#d14">-
</span><span style="color:#d14">      machine_id: rick-and-morty-the-anime</span><span style="color:#bbb">
</span><span style="color:#bbb">      </span><span style="color:#000;font-weight:bold">name: &#39;Rick and Morty</span>:<span style="color:#bbb"> </span>The<span style="color:#bbb"> </span>Anime<span style="color:#d14">&#39;
</span><span style="color:#d14">      work_type: anime_series
</span><span style="color:#d14">      canonical_status: derivative_continuity
</span><span style="color:#d14">      source_provider: Wikidata
</span><span style="color:#d14">      source_id: Q116508000
</span><span style="color:#d14">      source_url: &#39;</span>https://www.wikidata.org/wiki/Q116508000<span style="color:#d14">&#39;
</span><span style="color:#d14">      wikidata_id: Q116508000
</span><span style="color:#d14">      tvmaze_id: &#39;</span><span style="color:#099">62220</span><span style="color:#d14">&#39;
</span><span style="color:#d14">    -
</span><span style="color:#d14">      machine_id: non-canonical-adventures
</span><span style="color:#d14">      name: &#39;</span><span style="color:#000;font-weight:bold">Rick and Morty</span>:<span style="color:#bbb"> </span>The<span style="color:#bbb"> </span>Non-Canonical<span style="color:#bbb"> </span>Adventures<span style="color:#d14">&#39;
</span><span style="color:#d14">      work_type: short_collection
</span><span style="color:#d14">      canonical_status: non_canonical
</span><span style="color:#d14">      source_provider: Wikidata
</span><span style="color:#d14">      source_id: Q117358705
</span><span style="color:#d14">      source_url: &#39;</span>https://www.wikidata.org/wiki/Q117358705<span style="color:#d14">&#39;
</span><span style="color:#d14">      wikidata_id: Q117358705
</span><span style="color:#d14">      tvmaze_id: &#39;</span><span style="color:#099">55936</span><span style="color:#d14">&#39;
</span><span style="color:#d14">  ids:
</span><span style="color:#d14">    machine_id:
</span><span style="color:#d14">      type: string
</span><span style="color:#d14">
</span><span style="color:#d14">process:
</span><span style="color:#d14">  machine_id: machine_id
</span><span style="color:#d14">  name: name
</span><span style="color:#d14">  work_type: work_type
</span><span style="color:#d14">  canonical_status: canonical_status
</span><span style="color:#d14">  source_provider: source_provider
</span><span style="color:#d14">  source_id: source_id
</span><span style="color:#d14">  source_url: source_url
</span><span style="color:#d14">  wikidata_id: wikidata_id
</span><span style="color:#d14">  imdb_id: imdb_id
</span><span style="color:#d14">  tvmaze_id: tvmaze_id
</span><span style="color:#d14">  uid:
</span><span style="color:#d14">    plugin: default_value
</span><span style="color:#d14">    default_value: 1
</span><span style="color:#d14">
</span><span style="color:#d14">destination:
</span><span style="color:#d14">  plugin: &#39;</span>entity:rick_and_migraty_work&#39;<span style="color:#bbb">
</span><span style="color:#bbb">  </span><span style="color:#000;font-weight:bold">validate</span>:<span style="color:#bbb"> </span><span style="color:#000;font-weight:bold">true</span><span style="color:#bbb">
</span><span style="color:#bbb">
</span><span style="color:#bbb"></span><span style="color:#000;font-weight:bold">migration_dependencies</span>:<span style="color:#bbb">
</span><span style="color:#bbb">  </span><span style="color:#000;font-weight:bold">required</span>:<span style="color:#bbb">
</span><span style="color:#bbb">    </span>- rick_and_migraty_work<span style="color:#bbb">
</span></code></pre></td></tr></table>
</div>
</div>
  
  <p class="code-snippet__source">
    Source: <a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_migrate/migrations/rick_and_migraty_work_optional.yml?ref_type=heads" rel="noopener noreferrer" target="_blank">Source file on GitLab</a>
  </p>
  
</div>


<p><code>machine_id</code> matters more than the visible title: it is the stable identity that makes <code>migrate:import --update</code> update a previous destination instead of creating another work. The migration also depends on <code>rick_and_migraty_work</code>, establishing that the optional catalogue extends rather than replaces the main work.</p>
<p>Once the destination contains the two new work entities, the next operation can load the episode catalogue that belongs to each one. <strong>We keep those responsibilities in two migrations:</strong> one for <em>The Anime</em> and one for the non-canonical shorts.</p>
<h3 id="61-which-plugins-do-we-need">6.1. Which plugins do we need?</h3>
<p>Before implementing them, we should take stock of the tools: <strong>which resources already exist, and which piece genuinely needs to be custom?</strong> The decision should follow the migration contract rather than a preference for writing new code.</p>
<p>At source level, both migrations need the same reusable abstraction: <strong>the complete, approved episode catalogue for one specific TVmaze show</strong>. It must serve both <em>The Anime</em> and <em>The Non-Canonical Adventures</em> without hard-coding either one into the plugin.</p>
<p>Drupal Core provides the base for source plugins and covers sources such as the embedded data we just used. Migrate Plus could combine its generic <code>url</code> plugin with a JSON parser. That would be enough if the problem were merely to download a document and select a path, but our contract requires more: it must enforce a fixed show identity and an expected catalogue size.</p>
<p>Existing custom plugins do not fit either. <code>rick_and_morty_api</code> understands the canonical API&rsquo;s pagination and schema; reusing it for TVmaze would mix two remote contracts. The Fandom plugin resolves MediaWiki pages rather than episode catalogues.</p>
<p>Forcing either plugin into this job merely to avoid creating one class would reduce the visible line count while increasing coupling. More importantly, it would hide the actual conditions of this source: the caller must select one known TVmaze show, receive its complete episode catalogue, and reject a response that no longer matches the approved scope.</p>
<p>That leads to the custom source plugin <a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_migrate/src/Plugin/migrate/source/RickAndMigratyTvmazeEpisodes.php"><code>RickAndMigratyTvmazeEpisodes</code></a>. It receives a <code>show_id</code>, requests <code>/shows/{id}/episodes</code>, normalises each row, exposes the TVmaze ID as a stable key, supports a test base URL, caches responses, and can enforce <code>expected_count</code>. A catalogue mismatch fails for review instead of being silently accepted.</p>
<p><strong>The following simplified extract makes the core decision visible.</strong> HTTP and cache infrastructure are omitted so that the contract stands out: stable identity, mandatory configuration, and catalogue-size validation.</p>







<div class="code-snippet">
  <div class="highlight"><div style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4">
<table style="border-spacing:0;padding:0;margin:0;border:0;width:auto;overflow:auto;display:block;"><tr><td style="vertical-align:top;padding:0;margin:0;border:0;">
<pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 1
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 2
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 3
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 4
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 5
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 6
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 7
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 8
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 9
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">10
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">11
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">12
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">13
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">14
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">15
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">16
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">17
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">18
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">19
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">20
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">21
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">22
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">23
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">24
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">25
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">26
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">27
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">28
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">29
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">30
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">31
</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">32
</span></code></pre></td>
<td style="vertical-align:top;padding:0;margin:0;border:0;;width:100%">
<pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-php" data-lang="php"><span style="color:#999;font-weight:bold;font-style:italic">&lt;?php</span>

<span style="color:#998;font-style:italic">#[MigrateSource(&#39;rick_and_migraty_tvmaze_episodes&#39;)]
</span><span style="color:#998;font-style:italic"></span><span style="color:#000;font-weight:bold">final</span> <span style="color:#000;font-weight:bold">class</span> <span style="color:#458;font-weight:bold">RickAndMigratyTvmazeEpisodes</span> <span style="color:#000;font-weight:bold">extends</span> SourcePluginBase {

  <span style="color:#000;font-weight:bold">public</span> <span style="color:#000;font-weight:bold">function</span> <span style="color:#900;font-weight:bold">getIds</span>()<span style="color:#000;font-weight:bold">:</span> <span style="color:#000;font-weight:bold">array</span> {
    <span style="color:#000;font-weight:bold">return</span> [<span style="color:#d14">&#39;id&#39;</span> <span style="color:#000;font-weight:bold">=&gt;</span> [<span style="color:#d14">&#39;type&#39;</span> <span style="color:#000;font-weight:bold">=&gt;</span> <span style="color:#d14">&#39;integer&#39;</span>]];
  }

  <span style="color:#000;font-weight:bold">protected</span> <span style="color:#000;font-weight:bold">function</span> <span style="color:#900;font-weight:bold">initializeIterator</span>()<span style="color:#000;font-weight:bold">:</span> \Iterator {
    <span style="color:#008080">$showId</span> <span style="color:#000;font-weight:bold">=</span> (int) (<span style="color:#008080">$this</span><span style="color:#000;font-weight:bold">-&gt;</span><span style="color:#008080">configuration</span>[<span style="color:#d14">&#39;show_id&#39;</span>] <span style="color:#000;font-weight:bold">??</span> <span style="color:#099">0</span>);
    <span style="color:#000;font-weight:bold">if</span> (<span style="color:#008080">$showId</span> <span style="color:#000;font-weight:bold">&lt;</span> <span style="color:#099">1</span>) {
      <span style="color:#000;font-weight:bold">throw</span> <span style="color:#000;font-weight:bold">new</span> MigrateException(
        <span style="color:#d14">&#39;TVmaze requires a positive show_id.&#39;</span>,
      );
    }

    <span style="color:#008080">$rows</span> <span style="color:#000;font-weight:bold">=</span> <span style="color:#008080">$this</span><span style="color:#000;font-weight:bold">-&gt;</span><span style="color:#008080">loadAndNormalizeEpisodes</span>(<span style="color:#008080">$showId</span>);
    <span style="color:#008080">$expected</span> <span style="color:#000;font-weight:bold">=</span> (int) (
      <span style="color:#008080">$this</span><span style="color:#000;font-weight:bold">-&gt;</span><span style="color:#008080">configuration</span>[<span style="color:#d14">&#39;expected_count&#39;</span>] <span style="color:#000;font-weight:bold">??</span> <span style="color:#099">0</span>
    );

    <span style="color:#000;font-weight:bold">if</span> (<span style="color:#008080">$expected</span> <span style="color:#000;font-weight:bold">&gt;</span> <span style="color:#099">0</span> <span style="color:#000;font-weight:bold">&amp;&amp;</span> count(<span style="color:#008080">$rows</span>) <span style="color:#000;font-weight:bold">!==</span> <span style="color:#008080">$expected</span>) {
      <span style="color:#000;font-weight:bold">throw</span> <span style="color:#000;font-weight:bold">new</span> MigrateException(
        <span style="color:#d14">&#39;The TVmaze catalog has an unexpected size.&#39;</span>,
      );
    }

    <span style="color:#000;font-weight:bold">return</span> <span style="color:#000;font-weight:bold">new</span> \ArrayIterator(<span style="color:#008080">$rows</span>);
  }

}
</code></pre></td></tr></table>
</div>
</div>
  
  <p class="code-snippet__source">
    Source: <a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_migrate/src/Plugin/migrate/source/RickAndMigratyTvmazeEpisodes.php" rel="noopener noreferrer" target="_blank">Complete plugin on GitLab</a>
  </p>
  
</div>


<p>The full implementation injects <code>http_client</code> and <code>cache.data</code>, validates the URL and HTTP response, decodes JSON, and normalises fields such as <code>episode_code</code>, <code>rating_average</code>, and <code>description</code>. YAML remains responsible for the differences between the two migrations—the show, expected row count, and destination mapping—while the shared TVmaze contract lives in one reusable, unit-tested class.</p>
<p>The two migrations therefore draw on components from different parts of the Drupal ecosystem. <strong>Not every operation in their YAML files needs a custom plugin.</strong> We reserve project code for the TVmaze-specific contract and reuse Migrate API plugins for generic transformations. The resulting inventory is deliberately small:</p>
<ul>
<li><strong>Custom source — <code>rick_and_migraty_tvmaze_episodes</code>:</strong> this is the new <a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_migrate/src/Plugin/migrate/source/RickAndMigratyTvmazeEpisodes.php"><code>RickAndMigratyTvmazeEpisodes</code></a>. Although it extends Core&rsquo;s <code>SourcePluginBase</code>, its implementation belongs to our <code>rick_and_migraty_migrate</code> module. It queries TVmaze, enforces the approved-catalogue contract, normalises rows, and exposes <code>id</code> as the stable source identity.</li>
<li><strong>Core process — <code>default_value</code>:</strong> introduces known values that do not need to come from TVmaze. We use it for the receiving work key, rating and description providers, licence, and owner. Both migrations reuse the same plugin while supplying different values.</li>
<li><strong>Core process — <code>migration_lookup</code>:</strong> translates the optional work&rsquo;s stable source key into the destination entity ID created by <code>rick_and_migraty_work_optional</code>. Episodes are attached to their work without searching by title or duplicating query logic.</li>
<li><strong>Core process — <code>concat</code>:</strong> needed only for non-canonical content. It combines the <code>SHORT-</code> constant with the episode number to build <code>episode_code</code>; the Anime migration can use the code already normalised by the source plugin.</li>
<li><strong>Core destination — <code>entity:rick_and_migraty_episode</code>:</strong> this is Core&rsquo;s generic <code>entity</code> destination derivative. The plugin is part of Core even though <code>rick_and_migraty_episode</code> is our custom entity type. With <code>validate: true</code>, every entity is validated before its row finishes importing.</li>
</ul>
<p><strong>As a contributed module, Migrate Plus still provides the <code>migration_group: rick_and_migraty</code> metadata used to organise these definitions.</strong> It also supplied the generic <code>url</code> plus JSON-parser alternative considered earlier, but that option was deliberately rejected. In other words, no contributed plugin remains in the final source/process/destination pipeline: the executable plugins are the Core components listed above plus our custom source.</p>
<p>With the toolbox established, we can define one episode migration for each catalogue:</p>
<ul>
<li><a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_migrate/migrations/rick_and_migraty_episode_anime.yml"><code>rick_and_migraty_episode_anime</code></a> expects 10 episodes.</li>
<li><a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_migrate/migrations/rick_and_migraty_episode_noncanonical.yml"><code>rick_and_migraty_episode_noncanonical</code></a> expects 36 shorts.</li>
</ul>
<p>Both use <code>RickAndMigratyTvmazeEpisodes</code>: the configured <code>show_id</code> changes, but the plugin still normalises fields, retains the TVmaze episode ID, and validates the expected number of rows. Both then attach episodes to their work through Core&rsquo;s <code>migration_lookup</code>:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-yaml" data-lang="yaml"><span style="color:#000;font-weight:bold">process</span>:<span style="color:#bbb">
</span><span style="color:#bbb">  </span><span style="color:#000;font-weight:bold">work_key</span>:<span style="color:#bbb">
</span><span style="color:#bbb">    </span><span style="color:#000;font-weight:bold">plugin</span>:<span style="color:#bbb"> </span>default_value<span style="color:#bbb">
</span><span style="color:#bbb">    </span><span style="color:#000;font-weight:bold">default_value</span>:<span style="color:#bbb"> </span>rick-and-morty-the-anime<span style="color:#bbb">
</span><span style="color:#bbb">  </span><span style="color:#000;font-weight:bold">work</span>:<span style="color:#bbb">
</span><span style="color:#bbb">    </span><span style="color:#000;font-weight:bold">plugin</span>:<span style="color:#bbb"> </span>migration_lookup<span style="color:#bbb">
</span><span style="color:#bbb">    </span><span style="color:#000;font-weight:bold">migration</span>:<span style="color:#bbb"> </span>rick_and_migraty_work_optional<span style="color:#bbb">
</span><span style="color:#bbb">    </span><span style="color:#000;font-weight:bold">source</span>:<span style="color:#bbb"> </span><span style="color:#d14">&#39;@work_key&#39;</span><span style="color:#bbb">
</span><span style="color:#bbb">    </span><span style="color:#000;font-weight:bold">no_stub</span>:<span style="color:#bbb"> </span><span style="color:#000;font-weight:bold">true</span><span style="color:#bbb">
</span></code></pre></div><p>This is the natural use of <code>migration_lookup</code>: we know the original source key and the migration that created the destination. <code>no_stub: true</code> prevents an incomplete reference from being fabricated when the work is absent.</p>
<h2 id="7-locating-existing-entities-to-enrich-them">7. Locating existing entities to enrich them</h2>
<p>The other half of the work—and the core of this article—is not creating episodes. It is accepting an external row, determining which stored entity represents the same object, and adding information without recreating it. <strong>The hard question is how to prove that records from different systems describe the same thing.</strong></p>
<p>IMDb identifies an episode by its <code>tconst</code>. Drupal knows it through an internal entity ID, a work reference, season, and episode number. We need a shared identity that bridges both models.</p>
<h3 id="a-lookup-is-not-a-title-search">A lookup is not a title search</h3>
<p><strong>Searching by episode title is tempting, but fragile.</strong> Titles can be translated, corrected, punctuated differently, or repeated across works. Even an exact match today can stop matching after a routine editorial change.</p>
<p>A useful lookup identity must satisfy three conditions:</p>
<ol>
<li><strong>It must be stable:</strong> a presentation correction should not change it.</li>
<li><strong>It must be sufficiently specific:</strong> it should identify at most one local entity.</li>
<li><strong>It must be available on both sides:</strong> the external source and Drupal must express the same key or a verifiable equivalent.</li>
</ol>
<p>For regular episodes, we use work + season + episode number:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-text" data-lang="text">rick-and-morty + season 3 + episode 7
</code></pre></div><p>The work prevents <code>S03E07</code> from another series becoming a false positive. <strong>Season and episode locate the record within that work.</strong> IMDb&rsquo;s <code>tconst</code> is retained as the identity of the new rating observation rather than used to locate an episode created before that identifier was needed.</p>
<h3 id="three-kinds-of-lookup-in-a-drupal-migration">Three kinds of lookup in a Drupal migration</h3>
<ul>
<li><strong><code>migration_lookup</code> queries an earlier migration&rsquo;s map tables.</strong> It is the best option when the original source ID and the migration that created the destination are known.</li>
<li><strong><code>entity_lookup</code></strong>, provided by contributed modules in the Migrate ecosystem, <strong>searches for an entity by property.</strong> It is useful when there is no reusable migration map and one unique property can express the identity.</li>
<li>A <strong>custom process plugin</strong> can combine several entity types and properties, validate cardinality, and explicitly decide what to do with zero or multiple matches.</li>
</ul>
<p>No option is universally best. If we retained the original source ID and its map, <code>migration_lookup</code> gives us traceability almost for free. If the entity predates our migration, or the new source does not share that ID, we must locate it through its business identity. <strong>The IMDb → episode join requires work + season + episode,</strong> so Rick and Migraty uses a dedicated process plugin.</p>
<h3 id="the-source-prepares-the-external-half-of-the-identity">The source prepares the external half of the identity</h3>
<p>Before looking at the plugin, we need to understand how IMDb distributes these data. Rather than exposing one request that returns every <em>Rick and Morty</em> episode with its rating, <strong>IMDb publishes a collection of <a href="https://developer.imdb.com/non-commercial-datasets/">datasets for non-commercial use</a>.</strong> They are global snapshots of its catalogue, updated daily and divided by responsibility: title identity, series/episode relationships, ratings, cast, and other domains.</p>
<p>Every dataset is a UTF-8 TSV file compressed with Gzip. The first row contains headers, columns are separated by tabs, and <code>\N</code> represents a missing value. <strong>We are not downloading a small JSON document for our series; we are filtering and joining general-purpose files during ETL.</strong></p>
<p>Two files are required:</p>
<ul>
<li><strong><code>title.episode.tsv.gz</code> describes the episode&rsquo;s structural identity.</strong> Each row contains the episode <code>tconst</code>, the series <code>parentTconst</code>, <code>seasonNumber</code>, and <code>episodeNumber</code>. It answers <em>which episode is this, and to which series does it belong?</em>, but contains no rating.</li>
<li><strong><code>title.ratings.tsv.gz</code> contains the rating observation.</strong> For each <code>tconst</code>, it provides <code>averageRating</code>—the weighted mean of user ratings—and <code>numVotes</code>. It knows how a title was rated, but not its season, episode number, or parent series.</li>
</ul>
<p>The <code>tconst</code> is the join key between both files. The operation can be described in four steps:</p>
<ol>
<li>Read the series IMDb identifier from Drupal&rsquo;s work entity; this is the <code>parentTconst</code> we need.</li>
<li>Stream <code>title.episode.tsv.gz</code> and retain only episodes whose <code>parentTconst</code> matches that series.</li>
<li>Find each selected episode&rsquo;s score and vote count in <code>title.ratings.tsv.gz</code> through its <code>tconst</code>.</li>
<li>Emit a migration row that combines <code>tconst</code>, season, episode, rating, and votes.</li>
</ol>
<p><strong>Neither dataset is sufficient on its own:</strong> the first provides the context required to locate the Drupal episode; the second provides the new information with which we want to enrich it. The files are streamed and never committed to the project.</p>
<p><a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/feature/imdb-ratings-migrate-api/web/modules/custom/rick_and_migraty_migrate/migrations/rick_and_migraty_episode_rating_imdb.yml"><code>rick_and_migraty_episode_rating_imdb</code></a> implements this join through <a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/feature/imdb-ratings-migrate-api/web/modules/custom/rick_and_migraty_migrate/src/Plugin/migrate/source/RickAndMigratyImdbEpisodeRatings.php"><code>RickAndMigratyImdbEpisodeRatings</code></a>.</p>
<p>The plugin first loads the work by <code>machine_id</code> and obtains its IMDb series identifier. <strong>This lets it filter a huge dataset and emit only rows that belong to the work being enriched:</strong></p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-php" data-lang="php">$works = $this-&gt;entityTypeManager
  -&gt;getStorage(&#39;rick_and_migraty_work&#39;)
  -&gt;loadByProperties([&#39;machine_id&#39; =&gt; $machineId]);
$work = reset($works);

if ($work === FALSE) {
  throw new MigrateException(sprintf(
    &#39;The work %s must be imported before IMDb ratings.&#39;,
    $machineId,
  ));
}

$seriesId = trim((string) $work-&gt;get(&#39;imdb_id&#39;)-&gt;value);
</code></pre></div><p>This illustrates a broader principle: <strong>an enrichment migration should declare and verify its precondition.</strong> If the main work does not exist or lacks an IMDb ID, continuing to download and transform rating files makes no sense. Failing early gives a much more useful diagnosis than ending with zero matches.</p>
<p>After joining both files, every row entering Migrate has a deterministic shape:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-php" data-lang="php">$rows[] = [
  &#39;tconst&#39; =&gt; $titleId,
  &#39;series_tconst&#39; =&gt; $seriesId,
  &#39;season&#39; =&gt; $identity[&#39;season&#39;],
  &#39;episode&#39; =&gt; $identity[&#39;episode&#39;],
  &#39;episode_code&#39; =&gt; sprintf(
    &#39;S%02dE%02d&#39;,
    $identity[&#39;season&#39;],
    $identity[&#39;episode&#39;],
  ),
  &#39;average_rating&#39; =&gt; $ratings[$titleId][&#39;value&#39;],
  &#39;num_votes&#39; =&gt; $ratings[$titleId][&#39;votes&#39;],
  &#39;retrieved_at&#39; =&gt; $retrievedAt,
];
</code></pre></div><p>The <code>tconst</code> is the migration&rsquo;s source ID. Season and episode are the coordinates used to locate the corresponding Drupal entity. Score, votes, and retrieval time are the new information. <strong>Keeping those roles separate prevents a presentation value from becoming an accidental identity.</strong></p>
<h3 id="resolving-the-receiving-entity-in-the-process-pipeline">Resolving the receiving entity in the process pipeline</h3>
<p>The YAML definition passes season and episode to the custom <code>rick_and_migraty_episode_lookup</code> process plugin:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-yaml" data-lang="yaml"><span style="color:#000;font-weight:bold">process</span>:<span style="color:#bbb">
</span><span style="color:#bbb">  </span><span style="color:#000;font-weight:bold">episode</span>:<span style="color:#bbb">
</span><span style="color:#bbb">    </span><span style="color:#000;font-weight:bold">plugin</span>:<span style="color:#bbb"> </span>rick_and_migraty_episode_lookup<span style="color:#bbb">
</span><span style="color:#bbb">    </span><span style="color:#000;font-weight:bold">source</span>:<span style="color:#bbb">
</span><span style="color:#bbb">      </span>- season<span style="color:#bbb">
</span><span style="color:#bbb">      </span>- episode<span style="color:#bbb">
</span><span style="color:#bbb">    </span><span style="color:#000;font-weight:bold">work_machine_id</span>:<span style="color:#bbb"> </span>rick-and-morty<span style="color:#bbb">
</span></code></pre></div><p><a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/feature/imdb-ratings-migrate-api/web/modules/custom/rick_and_migraty_migrate/src/Plugin/migrate/process/RickAndMigratyEpisodeLookup.php"><code>RickAndMigratyEpisodeLookup</code></a> receives those two coordinates and adds the configured third component: the work identity. First, it requires exactly one work with that <code>machine_id</code>:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-php" data-lang="php">$works = $this-&gt;entityTypeManager
  -&gt;getStorage(&#39;rick_and_migraty_work&#39;)
  -&gt;loadByProperties([&#39;machine_id&#39; =&gt; $machineId]);

if (count($works) !== 1) {
  throw new MigrateException(sprintf(
    &#39;Expected exactly one work with machine_id %s; found %d.&#39;,
    $machineId,
    count($works),
  ));
}
</code></pre></div><p>It then uses that work ID to constrain the episode query:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-php" data-lang="php">$work = reset($works);
$episodes = $this-&gt;entityTypeManager
  -&gt;getStorage(&#39;rick_and_migraty_episode&#39;)
  -&gt;loadByProperties([
    &#39;work&#39; =&gt; $work-&gt;id(),
    &#39;season&#39; =&gt; $season,
    &#39;episode_number&#39; =&gt; $episodeNumber,
  ]);
</code></pre></div><p>The result is not treated as a boolean. Its cardinality has meaning:</p>
<ul>
<li><strong>Zero episodes:</strong> the IMDb row has no local receiver and is skipped with <code>MigrateSkipRowException</code>.</li>
<li><strong>One episode:</strong> the match is unambiguous, so the plugin returns its ID.</li>
<li><strong>More than one episode:</strong> the local catalogue violates the assumed uniqueness and the migration fails with <code>MigrateException</code>.</li>
</ul>
<p>This distinction matters. “We do not have this episode yet” can be a tolerable difference between catalogues. “We have two indistinguishable candidates” signals corruption or ambiguity that should not be hidden by selecting the first result. A safe lookup does more than find an entity: <strong>it protects the system from uncertain matches.</strong></p>
<p>The migration pipeline then maps that resolved entity ID into the observation&rsquo;s episode reference while preserving <code>tconst</code> as the observation&rsquo;s external identity.</p>
<h3 id="enrichment-does-not-mean-modifying-the-episode-directly">Enrichment does not mean modifying the episode directly</h3>
<p>The IMDb score is not written into a single episode field and does not replace TVmaze&rsquo;s rating. Doing that would destroy provenance. Instead, the model stores a separate <code>rick_and_migraty_episode_rating</code> observation entity linked to the resolved episode, so providers can coexist and every value retains its scale, votes, URL, licence, and retrieval date.</p>
<p>The central part of the migration looks like this:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-yaml" data-lang="yaml"><span style="color:#000;font-weight:bold">process</span>:<span style="color:#bbb">
</span><span style="color:#bbb">  </span><span style="color:#000;font-weight:bold">episode</span>:<span style="color:#bbb">
</span><span style="color:#bbb">    </span><span style="color:#000;font-weight:bold">plugin</span>:<span style="color:#bbb"> </span>rick_and_migraty_episode_lookup<span style="color:#bbb">
</span><span style="color:#bbb">    </span><span style="color:#000;font-weight:bold">source</span>:<span style="color:#bbb">
</span><span style="color:#bbb">      </span>- season<span style="color:#bbb">
</span><span style="color:#bbb">      </span>- episode<span style="color:#bbb">
</span><span style="color:#bbb">    </span><span style="color:#000;font-weight:bold">work_machine_id</span>:<span style="color:#bbb"> </span>rick-and-morty<span style="color:#bbb">
</span><span style="color:#bbb">  </span><span style="color:#000;font-weight:bold">id</span>:<span style="color:#bbb">
</span><span style="color:#bbb">    </span><span style="color:#000;font-weight:bold">plugin</span>:<span style="color:#bbb"> </span>rick_and_migraty_episode_rating_lookup<span style="color:#bbb">
</span><span style="color:#bbb">    </span><span style="color:#000;font-weight:bold">source</span>:<span style="color:#bbb">
</span><span style="color:#bbb">      </span>- <span style="color:#d14">&#39;@episode&#39;</span><span style="color:#bbb">
</span><span style="color:#bbb">      </span>- tconst<span style="color:#bbb">
</span><span style="color:#bbb">    </span><span style="color:#000;font-weight:bold">provider</span>:<span style="color:#bbb"> </span>IMDb<span style="color:#bbb">
</span><span style="color:#bbb">  </span><span style="color:#000;font-weight:bold">provider</span>:<span style="color:#bbb"> </span>constants/provider<span style="color:#bbb">
</span><span style="color:#bbb">  </span><span style="color:#000;font-weight:bold">external_id</span>:<span style="color:#bbb"> </span>tconst<span style="color:#bbb">
</span><span style="color:#bbb">  </span><span style="color:#000;font-weight:bold">raw_value</span>:<span style="color:#bbb"> </span>average_rating<span style="color:#bbb">
</span><span style="color:#bbb">  </span><span style="color:#000;font-weight:bold">normalized_value</span>:<span style="color:#bbb"> </span>average_rating<span style="color:#bbb">
</span><span style="color:#bbb">  </span><span style="color:#000;font-weight:bold">vote_count</span>:<span style="color:#bbb"> </span>num_votes<span style="color:#bbb">
</span><span style="color:#bbb">  </span><span style="color:#000;font-weight:bold">retrieved_at</span>:<span style="color:#bbb"> </span>retrieved_at<span style="color:#bbb">
</span><span style="color:#bbb">
</span><span style="color:#bbb"></span><span style="color:#000;font-weight:bold">destination</span>:<span style="color:#bbb">
</span><span style="color:#bbb">  </span><span style="color:#000;font-weight:bold">plugin</span>:<span style="color:#bbb"> </span><span style="color:#d14">&#39;entity:rick_and_migraty_episode_rating&#39;</span><span style="color:#bbb">
</span><span style="color:#bbb">  </span><span style="color:#000;font-weight:bold">validate</span>:<span style="color:#bbb"> </span><span style="color:#000;font-weight:bold">true</span><span style="color:#bbb">
</span><span style="color:#bbb">  </span><span style="color:#000;font-weight:bold">overwrite_properties</span>:<span style="color:#bbb">
</span><span style="color:#bbb">    </span>- episode<span style="color:#bbb">
</span><span style="color:#bbb">    </span>- raw_value<span style="color:#bbb">
</span><span style="color:#bbb">    </span>- normalized_value<span style="color:#bbb">
</span><span style="color:#bbb">    </span>- vote_count<span style="color:#bbb">
</span><span style="color:#bbb">    </span>- retrieved_at<span style="color:#bbb">
</span></code></pre></div><p>The first lookup answers <strong>“which episode should receive this datum?”</strong> The second answers <strong>“did this IMDb observation already exist before this migration started managing it?”</strong> They are two different identities and two different problems.</p>
<h3 id="adopting-data-that-predates-the-migration-map">Adopting data that predates the migration map</h3>
<p><strong>Migrate API maintains a map table between each row&rsquo;s <code>tconst</code> and the rating entity created at the destination.</strong> That map allows later <code>--update</code> runs to refresh the same observation. There is, however, an edge case: an earlier importer may already have created an IMDb observation before the Migrate-based implementation existed. The new map does not know its destination even though the domain entity is present.</p>
<p><a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/feature/imdb-ratings-migrate-api/web/modules/custom/rick_and_migraty_migrate/src/Plugin/migrate/process/RickAndMigratyEpisodeRatingLookup.php"><code>RickAndMigratyEpisodeRatingLookup</code></a> can adopt those entities. It searches through a compound identity made of episode, provider, and external ID:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-php" data-lang="php">$ratings = $this-&gt;entityTypeManager
  -&gt;getStorage(&#39;rick_and_migraty_episode_rating&#39;)
  -&gt;loadByProperties([
    &#39;episode&#39; =&gt; $episodeId,
    &#39;provider&#39; =&gt; $provider,
    &#39;external_id&#39; =&gt; $externalId,
  ]);

if (count($ratings) &gt; 1) {
  throw new MigrateException(sprintf(
    &#39;Multiple %s observations exist for episode %d and external ID %s.&#39;,
    $provider,
    $episodeId,
    $externalId,
  ));
}

return $ratings === [] ? NULL : (int) reset($ratings)-&gt;id();
</code></pre></div><p>If none exists, the plugin returns <code>NULL</code> and the destination creates an observation. If one exists, it returns the ID and the destination updates it. If several exist, the process stops: creating a third or updating an arbitrary one would only conceal the problem.</p>
<p><strong>This layer makes the migration idempotent in two distinct scenarios:</strong></p>
<ol>
<li><strong>After its first run,</strong> through the standard Migrate API map.</li>
<li><strong>When replacing an older importer,</strong> by adopting observations that existed before that map.</li>
</ol>
<p>Idempotency is not merely the ability to run a command twice. <strong>It means that repetition—or a transition between implementations—preserves identity, updates the correct datum, and does not accidentally increase the entity count.</strong> This is an important migration pattern: a new implementation can adopt older, correctly identified data into its tracking model.</p>
<h3 id="the-complete-journey-of-an-imdb-row">The complete journey of an IMDb row</h3>
<p>For one episode, the flow is now explicit:</p>
<ol>
<li><code>title.episode.tsv.gz</code> supplies <code>tconst</code>, parent series, season, and episode.</li>
<li><code>title.ratings.tsv.gz</code> supplies score and vote count for the same <code>tconst</code>.</li>
<li>The source plugin joins and normalises both records.</li>
<li><code>RickAndMigratyEpisodeLookup</code> resolves one local episode through work + season + episode.</li>
<li><code>RickAndMigratyEpisodeRatingLookup</code> adopts any matching pre-map observation.</li>
<li>The entity destination validates and writes the rating observation.</li>
<li>The Migrate map records <code>tconst</code> → rating entity ID for future updates.</li>
</ol>
<p>Seen this way, <strong>enrichment is not a second import of the content. It is a controlled join between two identity spaces.</strong> The episode remains the entity created by the primary migration; the secondary migration only proves which episode it is, creates or adopts a related observation, and adds information that was not previously available.</p>
<h3 id="myshows-applies-the-same-principle-with-a-different-identity">MyShows applies the same principle with a different identity</h3>
<p>IMDb forced us to join two global datasets through <code>tconst</code>. <strong>MyShows poses the same underlying problem—associating an external observation with an episode already stored—but exposes a different source and identity space.</strong> We use its public read-only API to complete the ratings for the 36 <em>Non-Canonical Adventures</em> shorts.</p>
<p>The API does not return everything in one response. <a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_migrate/src/MyShows/MyShowsClient.php"><code>MyShowsClient</code></a> makes two kinds of request:</p>
<ul>
<li><code>shows/74303</code> returns the remote <em>Non-Canonical Adventures</em> catalogue and its episode identifiers;</li>
<li><code>episodes/{episode_id}</code> returns one episode&rsquo;s details, including its aggregate rating and vote count.</li>
</ul>
<p>This access pattern explains why we keep a dedicated importer rather than modelling the operation as another declarative migration. We must validate the complete catalogue first and make an additional request for every accepted episode. The MyShows API is also deprecated and optional: <strong>isolating it behind a small client prevents its contract from leaking into the rest of the Migrate API pipeline.</strong></p>
<p>Identity is again the difficult part. The MyShows episode ID identifies the rating request and is retained as the observation&rsquo;s external ID, but the Drupal episodes were not created with it. The catalogue response does, however, contain a <code>tvrageLink</code> whose URL embeds the same episode&rsquo;s TVmaze ID. Drupal already knows that value because the preceding migration stored it as <code>tvmaze_id</code>.</p>
<p><a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_migrate/src/MyShows/MyShowsEpisodeRatingImporter.php"><code>MyShowsEpisodeRatingImporter</code></a> builds the bridge in five steps:</p>
<ol>
<li>Loads <code>non-canonical-adventures</code> and its episodes.</li>
<li>Indexes local episodes by <code>tvmaze_id</code>.</li>
<li>Loads the MyShows record for show <code>74303</code> and extracts TVmaze IDs from <code>tvrageLink</code>.</li>
<li>Resolves the matching local episode.</li>
<li>Loads the MyShows detail and stores the observation.</li>
</ol>
<p>Here again we prefer to fail when the contract drifts. <strong>Before writing, the importer requires exactly 36 local episodes and 36 remote episodes.</strong> A partial response is not interpreted as a successful import: a change in either catalogue must be reviewed before accepting new associations.</p>
<p>For every match, the remote detail must contain a score between 1 and 5 and a positive vote count. <a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_api/src/Rating/EpisodeRatingManager.php"><code>EpisodeRatingManager</code></a> retains the provider, original value and scale, votes, external ID and URL, and retrieval time. It writes by the compound identity <strong>episode + provider + external ID</strong>, so a retry updates the existing observation instead of duplicating it.</p>
<p>Finally, persistence and trust are not the same decision. MyShows observations with fewer than five votes remain visible and traceable, but do not participate in the episode&rsquo;s aggregate calculations. <strong>Importing a value does not require us to give it the same statistical weight as an observation backed by a larger sample.</strong></p>
<p>The concrete mechanism differs from IMDb, but the mental model remains the same: <strong>choose a stable shared key, require an unambiguous match, separate the receiving entity from the new observation, and make the write repeatable.</strong> That is what turns an additional data load into reliable enrichment.</p>
<h2 id="8-orchestrating-a-resumable-run">8. Orchestrating a resumable run</h2>
<p>The browser presents one secondary-migration action, but <a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_migrate/src/Optional/OptionalEnrichmentOrchestrator.php"><code>OptionalEnrichmentOrchestrator</code></a> coordinates seven steps:</p>
<ol>
<li>Prepare the system.</li>
<li>Import the complementary works.</li>
<li>Import <em>The Anime</em> episodes.</li>
<li>Import <em>The Non-Canonical Adventures</em> shorts.</li>
<li>Add MyShows ratings.</li>
<li>Add IMDb ratings to existing episodes.</li>
<li>Finalise and rebuild caches.</li>
</ol>
<p>Works, episodes, and IMDb ratings run through <code>migrate:import --update</code>; MyShows keeps its dedicated Drush importer. Each step records an <code>imported</code>, <code>updated</code>, <code>skipped</code>, or <code>failed</code> outcome in Drupal State. A new run retains successful steps and retries failed ones. The IMDb step additionally checks that persisted observations still exist before trusting historical success.</p>
<p>That extra check preserves an important distinction: <strong>“the command completed” is not the same as “the expected effect still exists”.</strong> A resumable ETL workflow needs both pieces of evidence before it decides that a step can safely be skipped.</p>
<p>Providers can be disabled independently for testing or local operation:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-bash" data-lang="bash"><span style="color:#008080">RICK_AND_MIGRATY_OPTIONAL_WIKIDATA</span><span style="color:#000;font-weight:bold">=</span><span style="color:#099">0</span>
<span style="color:#008080">RICK_AND_MIGRATY_OPTIONAL_TVMAZE</span><span style="color:#000;font-weight:bold">=</span><span style="color:#099">0</span>
<span style="color:#008080">RICK_AND_MIGRATY_OPTIONAL_MYSHOWS</span><span style="color:#000;font-weight:bold">=</span><span style="color:#099">0</span>
<span style="color:#008080">RICK_AND_MIGRATY_OPTIONAL_IMDB</span><span style="color:#000;font-weight:bold">=</span><span style="color:#099">0</span>
</code></pre></div><p>The web UI invokes each step separately and displays progress, but it is not the source of truth. Progress lives in Drupal State; identity lives in entities and Migrate maps. Reloading the browser does not force a restart.</p>
<h2 id="9-testing-the-integration-and-building-the-ratings-area">9. Testing the integration and building the ratings area</h2>
<p>A secondary migration does not finish when the last command returns zero. <strong>We must prove that works exist, episodes reference the right work, ratings belong to real episodes, and the interface can consume the resulting model.</strong></p>
<p>The project distributes that evidence across several tests:</p>
<ul>
<li><a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_api/tests/src/Kernel/WorkEpisodeRelationshipTest.php"><code>WorkEpisodeRelationshipTest</code></a> verifies work/episode relationships.</li>
<li><a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_api/tests/src/Kernel/EpisodeRatingManagerTest.php"><code>EpisodeRatingManagerTest</code></a> covers observation persistence and updates.</li>
<li><a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_migrate/tests/src/Unit/Plugin/migrate/source/RickAndMigratyTvmazeEpisodesTest.php"><code>RickAndMigratyTvmazeEpisodesTest</code></a> checks the remote-catalogue contract.</li>
<li><a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/feature/imdb-ratings-migrate-api/web/modules/custom/rick_and_migraty_migrate/tests/src/Unit/Plugin/migrate/source/RickAndMigratyImdbEpisodeRatingsTest.php"><code>RickAndMigratyImdbEpisodeRatingsTest</code></a> verifies deterministic dataset joins.</li>
<li><a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/feature/imdb-ratings-migrate-api/web/modules/custom/rick_and_migraty_migrate/tests/src/Unit/Plugin/migrate/process/RickAndMigratyEpisodeLookupTest.php"><code>RickAndMigratyEpisodeLookupTest</code></a> covers unique, missing, and ambiguous identities.</li>
<li><a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/feature/imdb-ratings-migrate-api/web/modules/custom/rick_and_migraty_migrate/tests/src/Unit/Plugin/migrate/process/RickAndMigratyEpisodeRatingLookupTest.php"><code>RickAndMigratyEpisodeRatingLookupTest</code></a> checks adoption of observations created before the map.</li>
<li><a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_migrate/tests/src/Unit/Optional/OptionalEnrichmentOrchestratorTest.php"><code>OptionalEnrichmentOrchestratorTest</code></a> covers the plan and resumption rules.</li>
<li><a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_migrate/tests/src/Functional/WorkCatalogRenderTest.php"><code>WorkCatalogRenderTest</code></a> verifies the enriched catalogue&rsquo;s functional output.</li>
</ul>
<p>For the interactive visualisation, we use <a href="https://www.chartjs.org/">Chart.js</a>. Version 4.6.1 renders a line chart whose horizontal axis represents an episode&rsquo;s position within a work and whose vertical axis shows its rating on a normalised ten-point scale. Each work is a separate series, so their trajectories can be compared without merging catalogues.</p>
<p><strong>Chart.js is responsible only for client-side presentation:</strong> it draws the chart, adapts its scales, displays episode details, providers, vote counts, and confidence levels in tooltips, updates the result after filtering, and turns each point into a link. It neither queries Drupal entities nor decides how ratings are calculated; those responsibilities remain in the backend.</p>
<p><a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_migrate/src/Controller/RatingInsightsController.php"><code>RatingInsightsController</code></a> loads works, episodes, and observations. It applies aggregate-eligibility rules and marks episodes whose only samples have low confidence. It sends that structure to the template and <code>drupalSettings</code>; <a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_migrate/js/rating-insights.js"><code>rating-insights.js</code></a> converts it into Chart.js datasets.</p>
<p>The public ratings area lets visitors:</p>
<ul>
<li>compare the main series, <em>The Anime</em>, and <em>The Non-Canonical Adventures</em>;</li>
<li>filter by work, season segment, and rating threshold;</li>
<li>follow rating trajectories on a chart;</li>
<li>inspect provider, vote count, and confidence;</li>
<li>open an episode profile from a point or card.</li>
</ul>
<p>The <a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/docs/docs/ratings-dashboard.md">ratings-dashboard guide</a> documents the filters and visualisation. <strong>The interface is not an isolated extra: it is visible proof that the secondary migration created and enriched the required relationships.</strong></p>
<p>
<span class="post-figure">
  <img src="/images/post/davidjguru_drupal_migrations_secondary_data_enrichment_three.webp" alt="Rick and Migraty ratings dashboard with work, season, and score filters and a comparative episode chart." loading="lazy" decoding="async">
  <span class="post-figure__caption">Interactive Rick and Migraty ratings dashboard</span>
</span>

</p>
<p>The screenshot shows the integrated result: three works as independent filters and their episode trajectories on one common scale. The controls narrow the comparison by work, season segment, and rating threshold; each point links to its episode. <strong>This verifies the complete chain: run enrichment, persist new observations, and turn them into a navigable interface.</strong></p>
<h2 id="10-patterns-worth-keeping">10. Patterns worth keeping</h2>
<p>At this point, we can separate Rick and Migraty&rsquo;s concrete details from the architectural decisions that sustained the whole process. TVmaze, IMDb, and MyShows are this example&rsquo;s providers; works, episodes, and ratings are its specific model. The broader problem is <strong>how to extend an already migrated catalogue without breaking its original contract, how to recognise existing entities, and how to incorporate multiple sources repeatably and verifiably.</strong></p>
<p>The conclusion is not that every secondary migration needs this exact collection of plugins and services. It is that dependencies must be explicit: required prior state, destination identity, ownership of each datum, and the evidence that proves enrichment completed successfully.</p>
<p>When those decisions remain separate, we can replace one provider, add another catalogue, or resume a failed import without turning the entire process into a special case that is difficult to understand and maintain.</p>
<p>From that perspective, several decisions are reusable:</p>
<ul>
<li><strong>Start from the use case.</strong> The chart revealed which data and model were missing.</li>
<li><strong>Separate the base catalogue from extensions.</strong> The primary migration remains small, stable, and independently useful.</li>
<li><strong>Assign one responsibility to each source.</strong> Identification, content creation, enrichment, and verification are different jobs.</li>
<li><strong>Choose the lookup from the identity.</strong> A migration map, entity property, or custom service solves a different problem.</li>
<li><strong>Keep deterministic keys.</strong> <code>machine_id</code>, season + episode, and <code>tvmaze_id</code> turn retries into updates.</li>
<li><strong>Store observations with provenance.</strong> Providers can coexist without the latest one overwriting earlier values.</li>
<li><strong>Validate persistent effects.</strong> A successful command is insufficient if it left no usable entity or rating.</li>
<li><strong>Design for resumption.</strong> External providers fail; isolate the damage and continue safely.</li>
<li><strong>Test the complete integration.</strong> Model, migrations, importers, and visualisation form one chain.</li>
</ul>
<p>A well-designed secondary migration is not an improvised appendix. <strong>It is a new ETL contract that understands the state created by the previous migration</strong> and knows exactly what it may create, locate, and enrich.</p>
<h2 id="11-running-the-secondary-migration-from-the-terminal">11. Running the secondary migration from the terminal</h2>
<p>The same process can be run from a terminal. This is especially useful during development because we can invoke providers separately, inspect Drush output, and repeat only a failed step. The contract remains unchanged: the primary migration must be complete, and the secondary flow must not begin by deleting the existing catalogue.</p>
<p>The project currently has no single shell wrapper for the complete secondary process. <a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/scripts/rick-and-migraty-migrate.sh"><code>scripts/rick-and-migraty-migrate.sh</code></a> handles the primary catalogue. The complementary sequence is declared by <a href="https://gitlab.com/davidjguru/rick-and-migraty/-/blob/main/web/modules/custom/rick_and_migraty_migrate/src/Optional/OptionalEnrichmentOrchestrator.php"><code>OptionalEnrichmentOrchestrator</code></a>, which also powers the browser&rsquo;s <strong>More cowbell</strong> action. Manual execution reproduces that same order with Drush.</p>
<h3 id="111-preparing-the-primary-migration">11.1. Preparing the primary migration</h3>
<p>From the repository root, start DDEV and run the primary runner when a complete base catalogue is not already present. <code>--fixtures</code> uses local API copies when available:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-bash" data-lang="bash">ddev start
scripts/rick-and-migraty-migrate.sh --fixtures
</code></pre></div><p>The script rebuilds caches, optionally resets previous imported data, imports primary entities and relationships, generates aliases, and runs Fandom enrichment. <strong>Do not run it with its default reset behaviour after starting secondary enrichment</strong>, because <code>ramt:migrate:reset</code> removes both primary and complementary entities, observations, and maps.</p>
<p>When the primary migration already exists, inspect its status instead of rebuilding it:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-bash" data-lang="bash">ddev drush migrate:status --group<span style="color:#000;font-weight:bold">=</span>rick_and_migraty
</code></pre></div><h3 id="112-running-the-secondary-steps-with-drush">11.2. Running the secondary steps with Drush</h3>
<p>Rebuild caches so Drupal discovers current definitions and plugins, then create optional works, import both TVmaze catalogues, and add MyShows and IMDb observations:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-bash" data-lang="bash">ddev drush cr

ddev drush migrate:import rick_and_migraty_work_optional <span style="color:#d14">\
</span><span style="color:#d14"></span>  --update --feedback<span style="color:#000;font-weight:bold">=</span><span style="color:#099">10</span>

ddev drush migrate:import rick_and_migraty_episode_anime <span style="color:#d14">\
</span><span style="color:#d14"></span>  --update --feedback<span style="color:#000;font-weight:bold">=</span><span style="color:#099">10</span>

ddev drush migrate:import rick_and_migraty_episode_noncanonical <span style="color:#d14">\
</span><span style="color:#d14"></span>  --update --feedback<span style="color:#000;font-weight:bold">=</span><span style="color:#099">10</span>

ddev drush ramt:migrate:myshows-ratings

ddev drush migrate:import rick_and_migraty_episode_rating_imdb <span style="color:#d14">\
</span><span style="color:#d14"></span>  --update --feedback<span style="color:#000;font-weight:bold">=</span><span style="color:#099">10</span>

ddev drush cr
</code></pre></div><p>Order matters. <code>rick_and_migraty_work_optional</code> persists work identities first; episode migrations can then resolve them through <code>migration_lookup</code>; MyShows finds non-canonical shorts by TVmaze identity; IMDb joins its datasets to main-series episodes. <code>--update</code> makes already imported sources processable without creating another copy.</p>
<p>MyShows uses a different command because it is not a YAML Migrate definition: <code>ramt:migrate:myshows-ratings</code> invokes the dedicated API importer and upserts every observation. IMDb retains Migrate maps and messages, so it uses the standard <code>migrate:import</code> command.</p>
<h3 id="113-verifying-the-result-and-resuming-after-a-failure">11.3. Verifying the result and resuming after a failure</h3>
<p>Inspect group status and IMDb messages after the run:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-bash" data-lang="bash">ddev drush migrate:status --group<span style="color:#000;font-weight:bold">=</span>rick_and_migraty
ddev drush migrate:messages rick_and_migraty_episode_rating_imdb
</code></pre></div><p>Do not stop at a zero exit code. Open <code>/ratings</code>, confirm that all three works are present, and verify that episode observations show provider, votes, and provenance links. This validates the persistent effect consumed by the interface rather than only command execution.</p>
<p>If a provider fails, repeat only its command. Stable keys, <code>--update</code>, and upserts make the sequence resumable. When a migration remains administratively stuck in <code>Importing</code>, release that specific migration before retrying:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-bash" data-lang="bash">ddev drush migrate:reset-status MIGRATION_ID
</code></pre></div><p>Replace <code>MIGRATION_ID</code> with the migration that is actually stuck. <strong>Do not use <code>ramt:migrate:reset</code> as an ordinary resume mechanism:</strong> it is a destructive cleanup of the complete local environment, not an isolated rollback of secondary enrichment.</p>
<h2 id="12-wq">12. :wq!</h2>
<p>The first migration built the world of Rick and Migraty. The second appeared when we looked at that world from another angle and discovered that territories and data were still missing.</p>
<h5 id="recommended-song-lafayette-afro-rock-band---hihache">Recommended song: Lafayette Afro Rock Band - Hihache</h5>


<figure class="trl-media-player" data-post-media-player>
  <figcaption class="trl-media-player__header">
    <span>TRL · AUDIO / VISUAL ARCHIVE</span>
    <span class="trl-media-player__brand" aria-hidden="true"></span>
  </figcaption>
  <div class="trl-media-player__screen">
    <div class="embed-responsive embed-responsive-16by9">
      
    </div>
  </div>
  <div class="trl-media-player__controls" aria-hidden="true">
    <span>33⅓ RPM</span>
    <span class="trl-media-player__groove"></span>
    <span>STEREO</span>
  </div>
</figure>

]]></content:encoded></item></channel></rss>